/*
 * @Author: xiaosihan 
 * @Date: 2024-08-03 18:20:44 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-22 22:12:03
 */

import { Button, Input, Modal } from "antd";
import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import styles from "./commentModal.module.less";
import clsx from "clsx";
import commentModalStore from "./commentModalStore";
import userStore from "@views/userStore";

import sendPNG from "./send.png";
import partCollaborateStore from "../../partCollaborateStore";
import partLableApi from "@api/partCollaborateApi";
import { isUndefined } from "lodash";
import hashHistory from "@hashHistory";
import partCollaborateDemoStore from "@views/pc/PartCollaborateDemo/partCollaborateDemoStore";
import utils from "@utils";
import dayjs from "dayjs";
import model3dRender from "../model3dRender";


interface Iprops {
    children?: ReactNode
}

// 评论标点组件
export default function CommentModal(props: Iprops) {

    const dom = useRef<HTMLDivElement | null>(null);
    const textareaDom = useRef<HTMLTextAreaElement | null>(null);
    const [show, setShow] = useState(commentModalStore.show);
    const [avatarUrl, setAvatarUrl] = useState(userStore.avatarUrl);
    const [placeholder, setPlaceholder] = useState(commentModalStore.placeholder);

    const isDemo = (location.hash === "#/partCollaborateDemo");

    useEffect(() => {
    }, []);

    useEffect(() => autorun(() => {
        setShow(commentModalStore.show);
        setAvatarUrl(userStore.avatarUrl);
        setPlaceholder(commentModalStore.placeholder);
    }), []);

    useEffect(() => autorun(() => {
        const { position } = commentModalStore;
        if (dom.current) {
            const domSize = dom.current.getBoundingClientRect();
            const viewSize = model3dRender.size;
            const x = Math.min(position.x, (viewSize.x - domSize.width));
            const y = Math.min(position.y, (viewSize.y - domSize.height));
            Object.assign(dom.current.style, { left: `${x}px`, top: `${y}px` });
        }
    }), []);

    //提交评论
    const sned = async () => {
        if (textareaDom.current) {
            commentModalStore.setShow(false);
            const { vPosition, modelIndex, modelCommentId, replyUserId } = commentModalStore;

            const { modelId } = partCollaborateStore;

            const local = JSON.stringify({
                x: vPosition.x,
                y: vPosition.y,
                z: vPosition.z,
                modelIndex
            });

            if (textareaDom.current.value) {
                if (!isUndefined(modelIndex)) {

                    if (isDemo) {
                        partCollaborateDemoStore.addPartLableData({
                            id: utils.uuid(),
                            content: textareaDom.current.value,
                            createBy: "",
                            createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                            location: local,
                            modelId: String(modelIndex),
                            title: "title",
                            updateBy: "",
                            updateTime: "",
                            userAvatarUrl: "./logo.png",
                            userId: "",
                            userName: "游客",
                            details: []

                        })
                    } else {
                        await partLableApi.add(modelId, textareaDom.current.value, local);
                        commentModalStore.setModelIndex();
                    }
                } else if (modelCommentId && replyUserId) {
                    await partLableApi.addCommentDetail(modelCommentId, replyUserId, textareaDom.current.value);
                    commentModalStore.setModelCommentId();
                    commentModalStore.setReplyUserId();
                }
            }

            partCollaborateStore.getPartLableData();
            textareaDom.current.value = "";
        }
    }

    return (
        <div
            ref={dom}
            className={clsx(styles.commentModal, show && styles.show)}
        >
            <img
                alt=""
                src={isDemo ? "./logo.png" : avatarUrl}
                className={styles.avatarUrl}
            />
            <div className={styles.btns} >
                <textarea
                    id=""
                    name=""
                    maxLength={200}
                    ref={textareaDom}
                    placeholder={placeholder}
                    className={styles.textarea}
                    onInput={e => {
                        const dom = (e.target as HTMLTextAreaElement);
                        dom.style.height = 'auto';
                        dom.style.height = dom.scrollHeight + 'px';
                    }}
                >
                </textarea>
                <Button
                    type="primary"
                    onClick={() => sned()}
                    style={{
                        width: 45,
                        height: 25
                    }}
                >
                    <img
                        alt=""
                        src={sendPNG}
                        className={styles.sned}
                    />
                </Button>
            </div>
        </div>
    );

}


// 评论弹窗
export function showCommentModal(title = "请输入评论") {
    return new Promise<string>((resolve, reject) => {
        let content = "";
        Modal.confirm({
            title: title,
            centered: true,
            content: (
                <div className={styles.commentModal} >
                    <Input.TextArea
                        placeholder={title}
                        maxLength={200}
                        rows={5}
                        onChange={e => {
                            content = e.target.value
                        }}
                    />
                </div>
            ),
            cancelText: "取消",
            onCancel() {
                reject();
            },
            okText: "确定",
            onOk() {
                if (content) {
                    resolve(content);
                } else {
                    reject();
                }
            }
        });

    });
}


